package com.framework.base.aqs;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chaolong.jin
 * @description
 * @date 2019/08/24 21:17
 */
public class SwitchThread {
    static volatile boolean fish = false;
    static AtomicInteger lock = new AtomicInteger(1);
    static BlockingQueue blockingQueue = new ArrayBlockingQueue(1);

    public static void main(String[] args) {
        FooBar fooBar = new FooBar();
        int n = 2;


        Thread thread1 = new Thread(new FooCallable(fooBar, n));
        Thread thread2 = new Thread(new BarCallable(fooBar, n));
        thread1.start();
        thread2.start();
    }

    static class FooBar {
        public void foo() {
            System.out.println("foo");
        }

        public void bar() {
            System.out.println("bar");
        }
    }

    static class FooCallable implements Runnable {
        private FooBar fooBar;
        private int n;

        public FooCallable(FooBar fooBar, int n) {
            this.fooBar = fooBar;
            this.n = n;
        }

        @Override
        public void run() {
            while (n > 0) {
                while (blockingQueue.peek() != null) {
                    Thread.yield();
                }
                fooBar.foo();
                fish = true;
                n--;
                blockingQueue.add(1);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class BarCallable implements Runnable {
        private FooBar fooBar;
        private int n;

        public BarCallable(FooBar fooBar, int n) {
            this.fooBar = fooBar;
            this.n = n;
        }

        @Override
        public void run() {
            while (n > 0) {
                while (blockingQueue.peek() == null) {
                    Thread.yield();
                }
                fooBar.bar();
                n--;
                blockingQueue.poll();
            }
        }
    }
}
